package com.lie.prepare.multi_thread.mypractice;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by lie on 2018/4/8.
 * attempt
 */
public class LockDemo {

    private ReentrantLock lock = new ReentrantLock();

    public void untimed(){
        boolean capture = lock.tryLock();
        try{
            System.out.println("try lock: "+ capture);
        }finally {
            if (capture)
                lock.unlock();
        }
    }

    public void timed(){
        boolean captured = false;

        try {
            captured = lock.tryLock(2, TimeUnit.SECONDS);
        }catch (InterruptedException e){
            throw  new RuntimeException(e);
        }

        try{
            System.out.println("try lock了指定的2秒~：" + captured);
        }finally {
            if (captured)
                lock.unlock();
        }

    }



    public static void main(String[] args){
        final LockDemo demo = new LockDemo();
        demo.untimed();
        demo.timed();

        new Thread(){
            {
                setDaemon(true);//设置为后台线程
            }

            @Override
            public void run() {
                //模拟一个线程，抓住了锁
                demo.lock.lock();
                System.out.println("神秘线程获取了锁");
            }
        }.start();

//        Thread.yield();//给神秘任务一个机会
        try {
            TimeUnit.SECONDS.sleep(1);//给神秘任务一个机会
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        demo.untimed();
        demo.timed();
    }






}
